using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using DotNetNuke.Modules.NBrightEspace.Components;
using DotNetNuke.Services.Exceptions;
using NBrightCore.common;
using NBrightCore.render;

namespace DotNetNuke.Modules.NBrightEspace
{

    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The EditNBrightEspace class is used to manage content
    /// </summary>
    /// -----------------------------------------------------------------------------
    public partial class DirectTrans : EspaceModuleBase
    {

        #region Event Handlers

        private const string EntityTypeCode = "INSTALLMENT%";
        private const string CtrlTypeCode = "DIRECTT";

        override protected void OnInit(EventArgs e)
        {
            //Set base EntityTypeCode, MUST be done for all NBright child ctrls before OnInit
            base.EntityTypeCode = EntityTypeCode; // entity type to pickup data
            base.CtrlTypeCode = CtrlTypeCode;  //ctrl type to pickup templates

            base.OnInit(e);

            //All list display functions are processed via the parent class, we just initiallize here.
            base.OnInitActivateList(true, true, MapPath(ControlPath));

        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (Page.IsPostBack == false)
            {
                PageLoad();
            }
        }

        private void PageLoad()
        {
            try
            {
                    //set default filter
                    if (String.IsNullOrEmpty(UInfo.SearchClearAfter))
                    {
                        var strSearchDate = DateTime.Now.ToString("o");
                        UInfo.SearchDate1 = strSearchDate;

                        var strF = " and (SUBSTRING([xmlData].value('(genxml/hidden/dtedate)[1]', 'nvarchar(50)'),1,7) = '" + strSearchDate.Substring(0, 7) + "')";
                        strF += "  and ([xmlData].value('(genxml/hidden/transferpayment)[1]', 'nvarchar(5)') = 'True')";

                        UInfo.SearchFilters = strF;
                        UInfo.SearchOrderby = " Order by [xmlData].value('(genxml/hidden/dtedate)[1]', 'nvarchar(50)') DESC ";
                        UInfo.SearchPageNumber = "1";
                        UInfo.SearchPageSize = "25";
                        UInfo.SearchReturnLimit = "0";
                        UInfo.SearchClearAfter = "false";
                        UInfo.Save();
                    }
                    // display list   
                    base.BindListData();
            }
            catch (Exception exc) //Module failed to load
            {
                UInfo.ClearSearchData();// remove search data incase error in data.
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }



        #endregion

        #region  "Events "


        public override void EventListItemCommand(object source, RepeaterCommandEventArgs e)
        {
            var cArg = e.CommandArgument.ToString();

        }

        public override void EventSearchItemCommand(object source, RepeaterCommandEventArgs e)
        {
            var cArg = e.CommandArgument.ToString();

            switch (e.CommandName.ToLower())
            {
                case "update":
                    UpdateData();
                    Response.Redirect(EditUrl(CtrlTypeCode));
                    break;
                case "prev":
                    PrevMonth();
                    Response.Redirect(EditUrl(CtrlTypeCode));
                    break;
                case "next":
                    NextMonth();
                    Response.Redirect(EditUrl(CtrlTypeCode));
                    break;
                case "view":
                    var strSearchDate = GenXmlFunctions.GetField((Repeater)source, "dateSearch");
                    SearchByDate(strSearchDate);
                    Response.Redirect(EditUrl(CtrlTypeCode));
                    break;
            }

        }


        private void SearchByDate(string strSearchDate)
        {
            if (Utils.IsDate(strSearchDate))
            {
                var dteSearchDate = Convert.ToDateTime(strSearchDate);
                strSearchDate = dteSearchDate.ToString("o");
                ResetSearchDate(strSearchDate);
            }
        }

        private void NextMonth()
        {
            var strSearchDate = UInfo.SearchDate1;
            if (Utils.IsDate(strSearchDate))
            {
                var dteSearchDate = Convert.ToDateTime(strSearchDate);
                strSearchDate = dteSearchDate.AddMonths(1).ToString("o");
                ResetSearchDate(strSearchDate);
            }
        }

        private void PrevMonth()
        {
            var strSearchDate = UInfo.SearchDate1;
            if (Utils.IsDate(strSearchDate))
            {
                var dteSearchDate = Convert.ToDateTime(strSearchDate);
                strSearchDate = dteSearchDate.AddMonths(-1).ToString("o");
                ResetSearchDate(strSearchDate);
            }
        }

        private void ResetSearchDate(string strSearchDate)
        {
            UInfo.SearchDate1 = strSearchDate;
            var strF = " and (SUBSTRING([xmlData].value('(genxml/hidden/dtedate)[1]', 'nvarchar(50)'),1,7) = '" + strSearchDate.Substring(0, 7) + "')";
            strF += "  and ([xmlData].value('(genxml/hidden/transferpayment)[1]', 'nvarchar(5)') = 'True')";
            UInfo.SearchFilters = strF;
            UInfo.SearchClearAfter = "false";
            UInfo.Save();
        }
 

        public override void EventBeforePageChange(object source, RepeaterCommandEventArgs e)
        {
            UpdateData();
        }

        #endregion

        #region "presistance methods"


        private void UpdateData()
        {
                if (Page.IsValid)
                {

                    var objCtrl = new EspaceController();

                    foreach (RepeaterItem dItem in base.CtrlList.Items)
                    {
                        //calculate total
                        var chkB = GenXmlFunctions.GetField(base.CtrlList, "chkDirectPay", dItem.ItemIndex);
                        if (chkB != "")
                        {
                            var insID = GenXmlFunctions.GetField(base.CtrlList, "ItemID", dItem.ItemIndex);
                            if (Utils.IsNumeric(insID))
                            {
                                var objInfo = ObjCtrl.Get(Convert.ToInt32(insID));                                
                                if (objInfo != null)
                                {
                                    var txtB = GenXmlFunctions.GetField(base.CtrlList, "txtComments", dItem.ItemIndex);
                                    //var strA = GenXmlFunctions.GetHiddenField(base.CtrlList, "dbldue", dItem.ItemIndex);
                                    var strA = objInfo.GetXmlProperty("genxml/hidden/dbldue");

                                    var xmlDoc = new XmlDataDocument();
                                    xmlDoc.LoadXml(objInfo.XMLData);
                                    GenXmlFunctions.ReplaceXmlNode(xmlDoc, "genxml/checkbox/chkdirectpay", chkB);
                                    GenXmlFunctions.ReplaceXmlNode(xmlDoc, "genxml/textbox/txtcomments", txtB);
                                    if (chkB=="True")
                                    {
                                        GenXmlFunctions.ReplaceXmlNode(xmlDoc, "genxml/hidden/dbltotaldue", "0");
                                        GenXmlFunctions.ReplaceXmlNode(xmlDoc, "genxml/hidden/dblactualpaid", Utils.FormatToSave(strA, TypeCode.Double));                                        
                                    }
                                    else
                                    {
                                        GenXmlFunctions.ReplaceXmlNode(xmlDoc, "genxml/hidden/dbltotaldue", Utils.FormatToSave(strA, TypeCode.Double));
                                        GenXmlFunctions.ReplaceXmlNode(xmlDoc, "genxml/hidden/dblactualpaid", "0");
                                    }

                                    objInfo.XMLData = xmlDoc.OuterXml;
                                    objCtrl.Update(objInfo);
                                }
                            }
                        }
                    }

                }
        }


        #endregion


    }

}